export type ThemeMode = 'dark' | 'light'

/**
 * @param theme 颜色模式
 * @desc 若指定主题则直接设置,没有则从本地存储中获取,本地也没有则设置为跟随系统主题
 */
export function setTheme(theme?: ThemeMode) {
  const setClass = (theme: ThemeMode) => {
    if (theme === 'dark') {
      document.documentElement.classList.add('dark')
      document.body.setAttribute('arco-theme', 'dark')
    } else {
      document.documentElement.classList.remove('dark')
      document.body.removeAttribute('arco-theme')
    }
  }

  if (theme) {
    setClass(theme)
  } else {
    theme = localStorage.getItem('theme') as ThemeMode
    if (theme === 'dark') {
      setClass('dark')
    } else if (theme === 'light') {
      setClass('light')
    } else {
      if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
        setClass('dark')
        theme = 'dark'
      } else {
        setClass('light')
        theme = 'light'
      }
    }
  }

  localStorage.setItem('theme', theme)
  return theme
}
